package com.xjlsoft.weather.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.xjlsoft.weather.dto.ResultEntity;
import com.xjlsoft.weather.dto.UserLoginDto;
import com.xjlsoft.weather.entity.User;
import com.xjlsoft.weather.entity.WeatherField;
import com.xjlsoft.weather.enums.ResultCodeEnum;
import com.xjlsoft.weather.enums.UserStatusEnum;
import com.xjlsoft.weather.mapper.UserMapper;
import com.xjlsoft.weather.mapper.WeatherFieldMapper;
import com.xjlsoft.weather.util.PasswordEncrypt;
import com.xjlsoft.weather.util.RedisUtil;
import com.xjlsoft.weather.util.ResultUtil;
import com.xjlsoft.weather.util.TokenUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

/**
 * @ Program : com.ljnt.blog.controller.LoginController @ Description : @ Author
 * : lj @ CreateDate : 2020-1-31 23:38
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理接口")
public class UserController {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserMapper usermapper;

	@Autowired
	private WeatherFieldMapper weatherFieldMapper;

	/**
	 * 用户登录操作<br>
	 * 表单方式提交参数
	 */
	@ApiOperation(value = "登录接口", notes = "登录认证通过后返回AccessToken(令牌)信息,令牌每5分钟过期,重新颁发令牌,每30分钟,需用户重新登录一次")
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public Object login(@Validated UserLoginDto userLoginDto, HttpServletResponse response)
			throws JsonProcessingException {
		String account = userLoginDto.getAccount();
		String password = userLoginDto.getPassword();

		logger.info("==========account=" + account + "  password=" + password);

		// 获取加密 字符串
		String pwd = PasswordEncrypt.encryptPassword(password);

		User userData = usermapper.getUserByAccount(account);

		if (userData == null) {
			return ResultUtil.resultMap(ResultCodeEnum.NO_USER);
		} else {
			if (UserStatusEnum.Freezing.getValue().equals(userData.getStatus())) {
				return ResultUtil.resultMap(ResultCodeEnum.USER_STATUS_ERROR);
			}
			if (!userData.getPassword().equals(pwd)) {
				return ResultUtil.resultMap(ResultCodeEnum.PASSWORD_ERROT);
			}
		}
		Long currentTimeMillis = System.currentTimeMillis();
		String token = TokenUtil.sign(account, password, currentTimeMillis);

		String st = TokenUtil.REFRESH_EXPIRE_TIME;
		System.out.println("token刷新时间=" + st);

		boolean res = RedisUtil.set(account, currentTimeMillis, Long.parseLong(TokenUtil.REFRESH_EXPIRE_TIME));
		System.out.println("redis 存放状态：" + res);
		response.setHeader("Authorization", token);
		response.setHeader("Access-Control-Expose-Headers", "Authorization");

		ResultEntity result = new ResultEntity(ResultCodeEnum.SUCCESS, userData, true);

		Map<String, Object> map = ResultUtil.resultMap(result);
		return map;
		// return new Result().OK();
	};

	/**
	 * 用户注销操作
	 * 
	 * 
	 */
	@ApiOperation(value = "登录接口", notes = "登录认证通后,注销账号操作")
	@ApiImplicitParam(name = "account", value = "登录账号", required = true, dataType = "String",paramType="query")
	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	@RequiresAuthentication // 当前Subject必须在当前session中已经过认证
	public Object logout(@RequestParam(value = "account", required = true) String account, HttpServletResponse response)
			throws JsonProcessingException {

		logger.info("=======用户注销===account=" + account);

		if (RedisUtil.hasKey(account)) {
			logger.info("====存在 需要删除的key  ");
			RedisUtil.del(account);
		}
		// return new Result().OK();
		ResultEntity result = new ResultEntity(ResultCodeEnum.SUCCESS, null, true);
		Map<String, Object> map = ResultUtil.resultMap(result);
		return map;
	};

	/**
	 * 用户注销操作
	 * 
	 * 
	 */
	@ApiOperation(value = "返回天气数据的属性名称和单位", notes = "返回天气数据的属性名称和单位")
	@ApiImplicitParam(name = "weatherFieldId", value = "主键id,1001气溶胶数据属性名称和单位 ,1002(地面数据)，1003(高空数据)，1004(辐射数据)", required = true, dataType = "String", paramType = "query") 
	@RequestMapping(value = "/getFieldsAndunitsById", method = RequestMethod.GET)
	public Object getFieldsAndunits(String weatherFieldId) {

		ResultEntity result=null;

		WeatherField wf = weatherFieldMapper.selectById(weatherFieldId);
	    if(wf !=null){
	    	result= new ResultEntity(ResultCodeEnum.SUCCESS, wf, true);
	    }else{
	    	result = new ResultEntity(ResultCodeEnum.FAILURE, null, true);
	    }
		Map<String, Object> map = ResultUtil.resultMap(result);
		return map;
	};

}
